package MTT::Controller::Login;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Login - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

use utf8;
use MTT::Form::Login;


use Data::Dumper;

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

	if ( $c->req->method eq 'POST' ) {
		my $username = $c->req->param('username');
		my $password = $c->req->param('password');
		utf8::encode($password);

		if ($username && $password) {
			if ( $c->authenticate({
						username => $username,
						password => $password }) ) {

				Log::Log4perl::MDC->put('login' => $c->user->username);
				$c->user_log->info('авторизация', 'login');

				my $back_url = '/';
				if ( my $cookie = $c->req->cookie('backurl') ) {
					$back_url = $cookie->value;
					$c->response->cookies->{backurl} = {value => '', expires => '-1d'};
				}
				
				$c->response->redirect( $back_url );
				return;
			}
			else {
				$c->stash(error_msg => 'Неправильное имя пользователя или пароль');
			}
		}
		else {
			$c->stash(error_msg => 'Неправильное имя пользователя или пароль');
		}

		$c->stash(
			form => MTT::Form::Login->new(),
			template => 'login.tt2'
		);
	}
	else {

		$c->stash(
			form => MTT::Form::Login->new(),
			template => 'login.tt2'
		);
	}

}


=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
